<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="query.keyword"
          placeholder="输入员工姓名全员搜索"
          prefix-icon="el-icon-search"
          @input="inputChange"
        ></el-input>
        <el-tree
          :data="data"
          :props="defaultProps"
          node-key="id"
          highlight-current
          default-expand-all
          :current-node-key="query.departmentId"
          @current-change="handleCurrentChange"
          :expand-on-click-node="false"
        ></el-tree>
      </div>
      <div class="right">
        <el-row type="flex" justify="end">
          <el-button v-permission="'add-employee'" type="primary" @click="$router.push('/employee/detail')"
            >添加员工</el-button
          >
          <el-button @click="showExcelDialog = true">Excel导入</el-button>
          <el-button @click="exportExcel">Excel导出</el-button>
        </el-row>

        <el-table :data="list" style="width: 100%">
          <el-table-column prop="staffPhoto" label="头像">
            <template #default="{ row }">
              <img
                :src="row.staffPhoto"
                v-if="row.staffPhoto"
                style="width: 30px"
              />
              <span v-else class="username">
                <!-- 字符串可以使用索引号来取对应的字符；
                      可选链操作字符配合索引号的使用方式 -->
                <!-- {{ row?.username?.[0] }} -->
                {{ row?.username?.charAt(0) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名"> </el-table-column>
          <el-table-column prop="mobile" label="手机号" sortable>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable>
          </el-table-column>
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{ row }">
              <span>{{
                row.formOfEmployment === 1
                  ? "正式"
                  : row.formOfEmployment === 2
                  ? "非正式"
                  : "未知"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门">
          </el-table-column>
          <el-table-column prop="timeOfEntry" label="入职时间" sortable>
          </el-table-column>
          <el-table-column prop="departmentName" label="操作">
            <template #default="{ row }">
              <el-button
                type="text"
                @click="$router.push('/employee/detail/' + row.id)"
                >查看</el-button
              >
              <el-button type="text" @click="openAssignRoleDialog(row.id)"
                >角色</el-button
              >

              <el-popconfirm
                title="确定要删除该员工么？"
                @confirm="delEmployee(row.id)"
              >
                <el-button type="text" slot="reference">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <el-row type="flex" justify="end">
          <el-pagination
            :current-page="query.page"
            :page-size="query.pagesize"
            layout="total, prev, pager, next"
            :total="total"
            @current-change="pageChange"
          >
          </el-pagination>
        </el-row>
      </div>
    </div>

    <import-excel
      :showExcelDialog.sync="showExcelDialog"
      @updata-excel-list="getEmployeeList"
    ></import-excel>

    <!--  el-dialog组件，它的内部实现，在触发右上角x号关闭时，执行力一个子向父通信的事件  updata:visible-->
    <el-dialog title="分配角色" :visible.sync="showRoleDialog">
      <el-checkbox-group v-model="checkRoleList" v-loading="loading">
        <el-checkbox :label="item.id" v-for="item in roleList" :key="item.id">{{
          item.name
        }}</el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getDepartmentList } from "@/api/department";
import { transListToTreeData } from "@/utils";
import {
  getEmployeeList,
  exportExcel,
  delEmployee,
  getEmployeeDetail,
  getRoleList,
  assignRole,
} from "@/api/employee";
import FileSave from "file-saver";
import ImportExcel from "./components/import-excel.vue";
export default {
  name: "Employee",
  components: { ImportExcel },
  data() {
    return {
      data: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      query: {
        page: 1,
        pagesize: 10,
        keyword: "",
        departmentId: 1, // 标记 当前高亮部门的 id
      },
      list: [], // 员工列表
      total: 0, // 员工总数
      showExcelDialog: false, // 控制导入excel的弹层显示和隐藏
      showRoleDialog: false, // 控制角色弹层的显示与隐藏
      checkRoleList: [],
      roleList: [], // 存储角色列表全集
      currentUserId: null, // 用来记录当前点击的用户id
      loading: false,
    };
  },
  // 侦听用法1： 配置项 比较固定刻板，无法实现灵活添加和取消侦听
  // watch: {
  //   'query.departmentId': {
  //     handler(newVal, oldVal) {
  //       this.getEmployeeList()
  //     },
  //     immediate: true
  //   }
  // },
  created() {
    this.getDepartmentList();
    // 侦听用法2： 更灵活（随时在需要的时候再添加侦听）刑恩更好（在不需要的时候取消监听）
    // 数据变化 => 驱动视图更新（render watcher) 驱动计算属性重新计算（computed watcher） 驱动侦听器执行处理函数（watcher）（本质上 vue内部对这3个的实现 都是watcher）
    this.unwatch = this.$watch(
      "query.departmentId",
      (newVal, oldVal) => {
        this.getEmployeeList();
      },
      // deep: true, flush: 'post' // flush是watch的回调函数的执行时机，post表示是在视图更新后触发
      { immediate: true }
    );
    // setTimeout(() => {
    //   this.unwatch() // 将来什么时候不再监听query.departmentId了，就可以执行this.unwatch()取消侦听
    // }, 5000)
  },
  methods: {
    async getDepartmentList() {
      this.data = transListToTreeData(await getDepartmentList(), 0);
    },
    handleCurrentChange(data) {
      this.query.departmentId = data.id;
      this.query.page = 1;
      this.getEmployeeList();
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.query);
      // console.log('1123', ret);
      this.list = rows;
      this.total = total;
    },
    pageChange(page) {
      console.log("111111", page);
      this.query.page = page;
      this.getEmployeeList();
    },

    inputChange() {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.query.page = 1;
        this.getEmployeeList();
      }, 500);
    },
    // 导出excel
    async exportExcel() {
      // 1. 调接口数据
      this.$notify.info({
        title: "消息",
        message: "正在下载",
      });
      const excelReasult = await exportExcel();
      // 2. 把接收的数据存储成一个文件
      // console.log('ret1111',ret);
      FileSave.saveAs(excelReasult, "员工信息表.xlsx");
    },
    async delEmployee(id) {
      // console.log(id)
      await delEmployee(id);
      this.$message.success("删除员工成功");
      if (this.list.length === 1 && this.query.page > 1) this.query.page--;
      this.getEmployeeList();
    },
    // 打开分配角色弹层
    async openAssignRoleDialog(id) {
      this.employeeId = id;
      this.showRoleDialog = true;
      this.loading = true;
      const { rows } = await getRoleList({ page: 1, pagesize: 100000 });
      this.roleList = rows;
      const { roleIds } = await getEmployeeDetail(id);
      this.checkRoleList = roleIds;
      this.loading = false;
    },
    // 弹层的确认按钮
    confirm() {
      // 1. 校验，不合法阻止
      // 2. 调接口
      assignRole({ id: this.employeeId, roleIds: this.checkRoleList });
      // 3. 提示
      this.$message.success("分配角色成功");
      // 4. 前端同步数据
      // 5. 关闭弹窗 清除校验规则+重置表单默认值
      this.showRoleDialog = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
